package tx.os3.opdracht1.deel2;

import java.io.File;
import java.util.LinkedList;
import java.util.List;
import java.util.Observable;

public class FileLister extends Observable {

    private File currentDir;
    private List<File> files;

    public FileLister() {
        this.files = new LinkedList<File>();
    }

    public File getCurrentDir() {
        return currentDir;
    }

    public void setCurrentDir(final File currentDir) {
        if(currentDir == null) {
            throw new IllegalArgumentException("Current dir cannot be null.");
        }
        if(!currentDir.isDirectory()) {
            throw new IllegalArgumentException(
                    "Given file must be a directory.");
        }
        this.currentDir = currentDir;
        this.files.clear();

        new Thread(new Runnable() {

            @Override
            public void run() {
                list(currentDir);
                setChanged();
                notifyObservers(files);
            }
        }).start();
    }

    private void list(File file) {
        if(file != null) {
            File[] children = file.listFiles();
            if(children != null) {
                for(File child : children) {
                    System.out.println(child);
                    this.files.add(child);
                    if(child != null && child.isDirectory()) {
                        this.list(child);
                    }
                }
            }
        }
    }
}